package com.xpgk.common.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.log.Log;
import com.xpgk.common.constants.ConstantWebContext;
import com.xpgk.common.controller.BaseController;
import com.xpgk.model.FrmRight;
import com.xpgk.xpsoft.user.UserService;

/**
 * 权限认证拦截器 描述： 1.处理权限验证 2.处理全局异常 3.处理权限相关的工具类方法
 */
public class AuthInterceptor implements Interceptor {

	private static final Log log = Log.getLog(AuthInterceptor.class);

	@Override
	public void intercept(Invocation invoc) {

		BaseController controller = (BaseController) invoc.getController();
		HttpServletRequest request = controller.getRequest();
		HttpServletResponse response = controller.getResponse();

		log.debug("获取用户请求的URI, (app_开头的为app)");
		String uri = invoc.getActionKey();
		if(!uri.startsWith("/app_")&&!uri.contains("/backstage")){
			controller.setAttr(ConstantWebContext.request_actionKey, uri);

			log.debug("获取URI对象!");
			FrmRight right = FrmRight.cacheGet(uri);
			if (null == right && uri.length() > 1) {
				String _uri = uri.substring(0, uri.indexOf("/", 1));
				right = FrmRight.cacheGet(_uri);
				if (null == right) {
					log.debug("URI不存在!uri = " + uri);
					toView(controller, "URI不存在!uri = " + uri);
					return;
				}
			}

			log.debug("获取当前用户!");
			int userID = controller.getCurUserID();
			if (userID != 1) {
				if (userID < 0) {
					log.debug("权限认证过滤器检测:未登录!");
					toView(controller, "权限认证过滤器检测:未登录!");
					return;
				}

				log.debug("用户权限验证!");
				if (!hasPrivilegeUrl(right.getID(), userID)) {// 权限验证
					log.debug("权限验证失败，没有权限!");
					toView(controller, "权限验证失败，没有权限!");
					return;
				}
			}
		}
		

		try {
			invoc.invoke();
		} catch (Exception e) {

		}

	}

	/**
	 * 判断用户是否拥有某个功能的操作权限
	 * 
	 * @param operatorIds
	 * @param userIds
	 * @return
	 */
	public static boolean hasPrivilegeUrl(int rightID, int userID) {
		return UserService.hasRight(userID, rightID);
	}

	/**
	 * 提示信息展示页
	 * 
	 * @param contro
	 * @param type
	 * @param msg
	 */
	private void toView(BaseController controller, String msg) {
		controller.setAttr("msg", msg);
		controller.renderError(404);
	}

}